<?php

    class m
    {
        //редирект
        public static function r ($url) 
        {
            header('Location: '.$url);
            exit;
        }

        public static function check_path ($name)
        {
            if ( is_string($name) )
            {
                $name = strtolower(trim($name));
                $name = str_replace('/','',$name);
                $name = str_replace('\\','',$name);
                $name = str_replace('/.','',$name);
                $name = str_replace('./','',$name);
                $name = str_replace('.\\','',$name);
                $name = str_replace('..','',$name);
                $name = str_replace('*','',$name);

                return $name;
            }
            else
            {
                return false;
            }
        }

        public static function data_save($file, $text)
        {
            $fp = @ fopen( DATA_PATH . $file, "w");

            if ($fp) 
            {
                @ flock($fp, LOCK_EX);
                @ fwrite($fp, $text);
                @ flock($fp, LOCK_UN);
            }

            @ fclose($fp);
        }

        public static function file_save($file, $text)
        {
            $fp = @ fopen( $file, "w");

            if ($fp) 
            {
                @ flock($fp, LOCK_EX);
                @ fwrite($fp, $text);
                @ flock($fp, LOCK_UN);
            }

            @ fclose($fp);
        }

        public static function json_read_today($name)
        {
            date_default_timezone_set('UTC');
            $day = ceil( time()/(60*60*24));

            if ( is_file(DATA_PATH . $name.'.'.$day.'.dat')) 
            {
                return self::json_data_read($name.'.'.$day.'.dat');
            }
            else
            {
                return array();
            }
        }        

        public static function json_save_today($name, $array)
        {
            date_default_timezone_set('UTC');
            $day = ceil( time()/(60*60*24));
            self::json_data_save($name.'.'.$day.'.dat', $array);
            return true;
        }

        public static function json_data_save($file, $text)
        {
            if ( is_array($text) )
            {
                $text = json_encode($text);    
            }

            $fp = @ fopen( DATA_PATH . $file, "w");

            if ($fp) 
            {
                @ flock($fp, LOCK_EX);
                @ fwrite($fp, $text);
                @ flock($fp, LOCK_UN);
            }

            @ fclose($fp);
        }

        //чтение файлов из папки data
        public static function data_read($file, $num = 0)
        {
            if ( !is_file(DATA_PATH . $file) ) return false;

            //если файл больше 100k
            if ($num > 100000 )
            {
                if ( filesize(DATA_PATH . $file) > 100000 ) return false;
            }

            $fp = fopen( DATA_PATH . $file, 'rb');

            if ($fp) 
            {
                @ flock($fp, LOCK_SH);

                $length = @filesize( DATA_PATH . $file ); 

                if ($num > 0)
                {

                    fseek ($fp, $length - $num);
                    $data = @fread($fp, $num);   
                }
                else
                {

                    if ($length) 
                    {
                        $data = @fread($fp, $length);
                    } 
                    else 
                    {
                        $data = '';
                    }
                }

                @flock($fp, LOCK_UN);
                @fclose($fp);

                return $data;
            }
            else 
            {
                return false;
            }

        }

        public static function read ($file)
        {
            $fp = fopen( DATA_PATH . $file, 'r');
            if ($fp) 
            {
                $length = filesize( DATA_PATH . $file ); 

                if ( $length == 0)
                {
                    return '';
                }
                else
                {
                    $buffer = '';
                    while (!feof ($fp)) 
                    {     
                        $buffer .= fgets($fp, 4096);     
                    } 

                    return $buffer;
                }

                @ fclose($fp);
            }  
            else
            {
                return '';
            }  
        }

        public static function _data_read($file, $un=false)
        {
            if ( is_file(DATA_PATH . $file))
            {
                return self::read($file);
            }
            else
            {
                return false;
            }
        }

        public static function json_data_read($file, $un=false)
        {
            if ( is_file(DATA_PATH . $file))
            {
                $data = self::read($file);

                if ( !empty($data))
                {
                    return json_decode($data , true);
                }
                else
                {
                    return ''; 
                }
            }
            else
            {
                return '';
            }

        }

        public static function version()
        {
            $data =  file_get_contents( dir_path('catalog').'VERSION');  
            $data = explode('/', $data);
            return $data[1];
        }

        public static function str_read($file, $param=array())
        {
            if ( !is_file(DATA_PATH . $file) )
            {
                return false;
            }


            $fp = fopen( DATA_PATH . $file, 'rb');

            @ flock($fp, LOCK_SH);

            if ($fp) 
            {
                $length = @filesize( DATA_PATH . $file );

                $data =  array();
                $m = array();
                $time = 0;

                if ($length) 
                {

                    while (!feof($fp)) 
                    {
                        $buffer = fgetss($fp, 4096);

                        if (!empty($buffer) )
                        {
                            $m = explode(";", $buffer);
                            unset($m[4]);

                            if ( count($param) > 0 )
                            {
                                foreach($param as $__s => $__d)
                                {
                                    if ( $m[1] == $__d)
                                    {      
                                        $time = $m[0];
                                        //unset($m[1]);
                                        unset($m[0]);
                                        $data[ $time ][ $__d ] = $m; 
                                    }
                                }  
                            }
                            else
                            {
                                $data[] = $m;
                            }
                        }
                    }
                } 


                @flock($fp, LOCK_UN);
                @fclose($fp);

                return $data;
            }
            else 
            {
                return false;
            }

        }


        //добавление записи в файл
        public static function data_add($file, $s)
        { 
            if ( is_file(DATA_PATH . $file))
            {
                $fp = fopen( DATA_PATH . $file, 'a');
            }
            else
            {
                $fp = fopen( DATA_PATH . $file, 'w');
            }

            if ($fp) 
            {
                @ flock($fp, LOCK_SH);
                fwrite($fp, $s."\r\n");

                @flock($fp, LOCK_UN);
                @fclose($fp);
            }
        }

        //обрезаем текст c учетом слов
        public static function truncate_words($text, $limit=200)
        {
            if ( is_string($name) )
            {
                $text=mb_substr($text,0,$limit);
                /*если не пустая обрезаем до  последнего  пробела*/
                if(mb_substr($text,mb_strlen($text)-1,1) && mb_strlen($text)==$limit)
                {
                    $textret=mb_substr($text,0,mb_strlen($text)-mb_strlen(strrchr($text,' ')));
                    if(!empty($textret))
                    {
                        return $textret;
                    }
                }
                return $text;
            }
            else
            {
                return false;
            }
        }

        //обрезаем текст без учета обрезания слов
        public static function cutString($string, $len = '50') 
        {
            if ( is_string($string) )
            {
                if ( mb_strlen($string) <= $len) 
                {
                    return $string;
                }

                return mb_substr($string, 0, $len) . "..";
            }
            else
            {
                return false;
            }
        }

        //определение потребляемой памяти
        public static function memory()
        {
            if (!function_exists('memory_get_peak_usage'))
            {
                return  round( memory_get_usage()/1024/1024, 2);
            }
            else
            {
                return round( memory_get_peak_usage()/1024/1024, 2);  
            }
        }

        //возвращает список файлов в папке
        public static function file_list ( $dir )
        {

            $files = array();
            if ( $dir [ strlen( $dir ) - 1 ] != '/' )
            {
                $dir .= '/'; //добавляем слеш в конец если его нет
            }

            $nDir = opendir( $dir );

            while ( false !== ( $file = readdir( $nDir ) ) )
            {
                if ( $file != "." AND $file != ".." and $file != '.htaccess' and $file != '.svn' )
                {
                    if ( !is_dir( $dir . $file ) )
                    { 
                        //если это не директория
                        $files [] = $file;
                    }
                }
            }

            closedir( $nDir );

            return $files;
        }

        //список категорий
        public static function dir_list ( $dir )
        {

            if ( $dir [ strlen( $dir ) - 1 ] != '/' )
            {
                $dir .= '/'; //добавляем слеш в конец если его нет
            }

            $nDir = opendir( $dir );
            $files = array();

            while ( false !== ( $file = readdir( $nDir ) ) )
            {
                if ( $file != "." AND $file != ".." )
                {
                    if ( is_dir( $dir . $file ) )
                    { 
                        //если это не директория
                        $files [] = $file;
                    }
                }
            }

            closedir( $nDir );

            return $files;
        }


        public static function data_array ()
        {
            $array = self::file_list(DATA_PATH);
            $op = array();
            if ( is_array($array) and count($array) > 0)
            {

                foreach ($array as $val)
                {
                    $opt = explode('.', $val);

                    if (count($opt) > 1)  
                    {
                        $format = trim( strtolower(  $opt[count($opt)-1] ) );

                        if ($format == 'dat')
                        {
                            unset($opt[count($opt)-1]);
                            $name = $opt[0];
                            unset($opt[0]);

                            if ( isset($opt[1]))
                            {
                                $op[ $name ][ ] = $opt[1]; 
                            }
                        }
                    }   
                }
            }

            return $op;
        }
        //выпадающее меню select
        public static function form_select ($value, $option,   $parameters = '')
        {
            $form = "<select {$parameters}>";

            if ( is_array( $option ) && count( $option ) > 0 )
            {
                foreach ($option as $_value)
                {
                    if ( $value == $_value)
                    {
                        $selected = 'selected="selected"';
                    }
                    else
                    {
                        $selected = '';  
                    }

                    $form .= '<option '.$selected.' value="'.$_value.'">'.$_value.'</option>';
                }    
            }

            $form .= '</select>';

            return $form;
        }

        /*
        $numr - всего кол. позиций
        $max_count - кол. позиций на страницу
        */
        public static function pages_menu($numr, $max_count, $c_page, $param = '')
        {
            $_param = '';
            $select = '';

            if ( isset($param['page_name']) ) $page_name = $param['page_name'];
            else $page_name = 'page';

            if (isset($param['param']) && count($param['param'])>0)
            {
                $_one = 1;

                if (isset($_GET['sorting']))
                {
                    $param['param']['sorting'] = $_GET['sorting'];
                }
                else
                {
                    $param['param']['sorting'] = 'name';
                }

                foreach ($param['param'] as $_param_name => $_param_value)
                {
                    if ($_one == 1)
                    {          
                        $_param .= $_param_name.'='.$_param_value;
                        $_one = 2;
                    }
                    else $_param .= '&'.$_param_name.'='.$_param_value;

                }
            }

            $file_name = $param['file_name'];

            $page_num = ceil($numr / $max_count);
            $stp = '';

            if (empty($c_page)) 
            {
                $_num = 1;
            }
            else
            {  
                $_num = (int)$c_page;
                if ($_num < 1) $_num = 1;
            } 

            if ($_num != 1) $stp .= '<li><a href="'. $page_name.'=1&'.$_param.'" >Первая</a></li>'."\n";

            if ($_num != 1) $stp .= '<li><a href="'.$page_name.'='.($_num-1).'&'.$_param.'" >&laquo;'.'</a></li>'."\n";;

            $select .= '<select class="pages_menu_select" id="pages_menu">';


            for ($i=1; $i<=$page_num; $i++ )
            {
                if ($i == $_num)
                {
                    $select .= '<option value="'.$i.'" selected>'.$i.'</option>';
                }
                else
                {
                    $select .= '<option value="'.$i.'" >'.$i.'</option>';
                }
            }

            $select .= '</select>';

            $stp.= '<li class="current">'.$select."</li>";

            if ($_num != $page_num) $stp .= '<li><a href="'. $page_name.'='.($_num+1).'&'.$_param.'" >&raquo;'.'</a></li>';

            if ($_num != $page_num) $stp .= '<li><a href="'. $page_name.'='.($page_num).'&'.$_param.'" >Последняя</a></li>';

            return $stp;
        }

        //подключение класса simple
        public static function simple()
        {
            include_once( dirname( __FILE__) .'/simple.php' );
        }

        //инклудит класс
        public static function c($name)
        {
            include_once( CLASS_PATH . $name .'.php'); 
        }

        public static function clean_ch($val)
        {
            $val = str_replace('- -', '', $val);
            $val = trim($val);
            /*
            if ($val[ count($val)-1] == '.')
            {
            substr($val, 0, strlen($val)-1);
            }

            $val = trim($val);*/

            return $val;
        }

        public static function shuffle_assoc($array) 
        { 
            if ( is_array($array) and count($array) > 0 )
            {
                $i = 0;
                $shuffle_array = array();
                $array_key = array();
                $array_val = array();
                $new_array = array();

                foreach ($array as $key => $val)
                {
                    $shuffle_array[$i] = $i;
                    $array_key[$i] = self::clean_ch($key);
                    $array_val[$i] = self::clean_ch($val);
                    $i++;
                }        

                shuffle($shuffle_array);

                foreach($shuffle_array as $tmp => $id)
                {
                    $new_array[ $array_key[ $id ] ] = $array_val[ $id ];
                }

                return $new_array;
            }
            else
            {
                return false;
            }
        } 

        public static function cleanname($name) 
        {
            //     $replace_param='/[^a-zA-Z0-9]/';
            $replace_param='/[^a-zA-Zа-яА-Я0-9]/';
            $cyrillic = array("ж", "ё", "й","ю", "ь","ч", "щ", "ц","у","к","е","н","г","ш", "з","х","ъ","ф","ы","в","а","п","р","о","л","д","э","я","с","м","и","т","б","Ё","Й","Ю","Ч","Ь","Щ","Ц","У","К","Е","Н","Г","Ш","З","Х","Ъ","Ф","Ы","В","А","П","Р","О","Л","Д","Ж","Э","Я","С","М","И","Т","Б");
            $translit = array("zh","yo","i","yu","","ch","sh","c","u","k","e","n","g","sh","z","h","",  "f",  "y",  "v",  "a",  "p",  "r",  "o",  "l",  "d",  "ye", "ya", "s",  "m",  "i",  "t",  "b",  "yo", "I",  "YU", "CH", "",  "SH", "C",  "U",  "K",  "E",  "N",  "G",  "SH", "Z",  "H",  "",  "F",  "Y",  "V",  "A",  "P",  "R",  "O",  "L",  "D",  "Zh", "Ye", "Ya", "S",  "M",  "I",  "T",  "B");
            $name = str_replace($cyrillic, $translit, $name);    
            //  $name = preg_replace($replace_param,'-',$name);    
            return $name;
        }

        public static function _die($text, $func = '', $di = true)
        {  
            if ( $di == true)
            {
                self::data_add('error.txt', time().";".$func.";".$text.'; die=yes');
                die($text);
            }    
            else
            {
                self::data_add('error.txt', time().";".$func.";".$text.'; die=no');
            }            
        }

    }

    function bazinga_error ($errno, $errstr, $errfile, $errline)
    {
        echo "<b>Custom error:</b> [$errno] $errstr<br />";
        echo " Error on line $errline in $errfile<br />";
        //m::_die("[$errno] $errstr line $errline in $errfile");
    }

    // set_error_handler("bazinga_error");

    //отлавливаем ошибки
    function bazinga_handler()
    {
        $error = error_get_last();
        if ( !empty($error) and $error['type'] != 2048)
        {
            echo $error['type'].': '. $error['message'] .':'.$error['file'].':'.$error['line'];  

            //если фатальная ошибка вывалилась во время выполнения задачи - завершаем задачу
            if ( !is_null(t::$status) and t::$status == 2)
            {
                t::status(t::$name, 1);
                $data = array();
                if ( isset( $_GET['type'] ) and $_GET['type']  == 'json')
                {
                    $data['file'] =  '<font color="red">fatal error!</font>';
                    echo json_encode($data);  
                }
                else
                {
                    echo $data['file']; 
                }
                m::_die('task',t::$name, true);
            }
        }
    }

    //отлавливаем фатальные ошибки
    register_shutdown_function('bazinga_handler');
?>
